package com.hjf.booking.security.config;

import com.alibaba.fastjson.JSON;
import com.hjf.booking.constants.BaseResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hjf
 * @date 2021-03-11 18:54
 */

public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        BaseResponse loginResponse = new BaseResponse();
        loginResponse.setCode(HttpStatus.UNAUTHORIZED.value());
        loginResponse.setMessage(exception.getMessage());
        //设置响应编码为utf-8，避免中文响应乱码
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(loginResponse));
    }

}
